package com.example.smartvillage.utils;

import android.util.Log;

import com.example.smartvillage.R;
import com.example.smartvillage.model.WeatherData;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class Weather {

    // 天气情况查询接口地址
    final private static String API_URL = "https://apis.juhe.cn/simpleWeather/query";
    final private static String TAG = "天气";

    /**
     * 根据城市名查询天气情况
     *
     * @param cityName 查询的城市名
     * @param apiKey 使用的ApiKey
     */
    public static WeatherData queryWeather(String cityName, String apiKey) {
        Map<String, Object> params = new HashMap<>();//组合参数
        params.put("city", cityName);
        params.put("key", apiKey);
        String queryParams = urlencode(params);

        String response = doGet(API_URL, queryParams);
        try {
            WeatherData weatherData = new Gson().fromJson(response, WeatherData.class);
            int error_code = weatherData.getError_code();
            if (error_code == 0) {
                Log.d(TAG, "queryWeather: 调用接口成功");

                return weatherData;
            } else {
                Log.d(TAG, "queryWeather: 调用接口失败，原因：" + weatherData.getReason());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int getWeatherIcon(String weatherId) {
        int iconId;
        switch (weatherId) {
            case "00":
                iconId = R.drawable.weather_sunny;
                break;
            case "01":
                iconId = R.drawable.weather_cloudy;
                break;
            case "02":
                iconId = R.drawable.weather_overcast;
                break;
            case "03":
                iconId = R.drawable.weather_shower;
                break;
            case "04":
                iconId = R.drawable.weather_thunder_shower;
                break;
            case "05":
                iconId = R.drawable.weather_thunder_shower_with_hail;
                break;
            case "06":
                iconId = R.drawable.weather_sleet;
                break;
            case "07":
                iconId = R.drawable.weather_drizzle;
                break;
            case "08":
                iconId = R.drawable.weather_moderate_rain;
                break;
            case "09":
                iconId = R.drawable.weather_heavy_rain;
                break;
            case "10":
                iconId = R.drawable.weather_rainstorm;
                break;
            case "11":
                iconId = R.drawable.weather_downpour;
                break;
            case "12":
                iconId = R.drawable.weather_torrential_rain;
                break;
            case "13":
                iconId = R.drawable.weather_snow_shower;
                break;
            case "14":
                iconId = R.drawable.weather_light_snow;
                break;
            case "15":
                iconId = R.drawable.weather_moderate_snow;
                break;
            case "16":
                iconId = R.drawable.weather_heavy_snow;
                break;
            case "17":
                iconId = R.drawable.weather_blizzard;
                break;
            case "18":
                iconId = R.drawable.weather_foggy;
                break;
            case "19":
                iconId = R.drawable.weather_sleet;
                break;
            case "20":
                iconId = R.drawable.weather_sandstorm;
                break;
            case "29":
                iconId = R.drawable.weather_dusty;
                break;
            case "30":
                iconId = R.drawable.weather_blowing_sand;
                break;
            case "31":
                iconId = R.drawable.weather_strong_sandstorm;
                break;
            case "53":
                iconId = R.drawable.weather_haze;
                break;

            default:
                throw new IllegalStateException("Unexpected value: " + weatherId);
        }
        return iconId;
    }

    /**
     * get方式的http请求
     *
     * @param httpUrl 请求地址
     * @return 返回结果
     */
    private static String doGet(String httpUrl, String queryParams) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpUrl + "?" + queryParams);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(5000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(6000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();
                // 封装输入流，并指定字符集
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                // 存放数据
                StringBuilder sbf = new StringBuilder();
                String temp;
                while ((temp = bufferedReader.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append(System.getProperty("line.separator"));
                }
                result = sbf.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();// 关闭远程连接
            }
        }
        return result;
    }

    /**
     * 将map型转为请求参数型
     *
     */
    private static String urlencode(Map<String, ?> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, ?> i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String result = sb.toString();
        result = result.substring(0, result.lastIndexOf("&"));
        return result;
    }
}
